// pages/essay-editor.js
import {requestHeader, BASE_URL, fetchEssayTypeList, publishEssay, fetchEssayDetail} from '../../../utils/request'
import Toast from 'tdesign-miniprogram/toast/index';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    originFiles: [],
    essayType: 0,
    essay: {},
    essayId: 0,
    typeValue: [],
    typeName: '',
    title: '',
    content: '',
    imageList: [],
    typeList: [],
    defaultFiles: [],
    pickerVisible: false,
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
    config: {
      count: 1,
    },
    submitDisabled: false,
    pageLoading: false
  },

  handleTypePicker() {
    this.setData({ pickerVisible: true });
  },

  onColumnChange(e) {
    console.log('picker pick:', e);
  },

  onPickerChange(e) {
    console.log("onPickerChange", e);
    this.setData({ 
      typeName: e.detail.label[0],
      typeValue: e.detail.value[0]
    });
  },

  onPickerCancel(e) {
    const { key } = e.currentTarget.dataset;
    console.log(e, '取消');
    this.setData({
      [`${key}Visible`]: false,
    });
  },

  onTitlePicker() {
    this.setData({ cityVisible: true, cityTitle: '选择城市' });
  },

  onWithoutTitlePicker() {
    this.setData({ city2Visible: true, city2Title: '' });
  },

  handleUpload(e1, e2) {
    console.log("handleUpload", e1, e2);
  },
  handleSuccess(e) {
    console.log("handleSuccess", e);
    const { files } = e.detail;
    this.setData({
      originFiles: files,
    });
  },
  handleRemove(e) {
    console.log("handleRemove", e);
    const { index } = e.detail;
    const { originFiles } = this.data;
    originFiles.splice(index, 1);
    this.setData({
      originFiles,
    });
  },
  handleClick(e) {
    console.log(e.detail.file);
  },
  handleComplete(e) {
    console.log("handleComplete", e);
  },
  handleAdd(files) {
    const fileList = files.detail.files;
    const file = fileList[0];
    const self = this;
    const _imagesList = this.data.imageList;
    self.setData({
      pageLoading: true
    })
    wx.uploadFile({
      filePath: file.url,
      name: 'file',
      url: BASE_URL + "/file/upload",
      header: requestHeader(),
      success(res) {
        let r = JSON.parse(res.data)
        console.log("upload success", r.data);
        _imagesList.push(r.data);
        self.setData({
          imageList: _imagesList
        })
      },
      fail(res) {
        console.log("upload fail", res);
      },
      complete(res) {
        self.setData({
          pageLoading: false
        })
      }
    })
    console.log(this.data.imageList);
  },
  handleTitle(e) {
    console.log("handleTitle", e);
    this.setData({
      title: e.detail.value
    })
  },
  handleContent(e) {
    console.log("handleContent", e);
    this.setData({
      content: e.detail.value
    })
  },

  validParam(params) {
    if (!params.imageUrls || params.imageUrls.length == 0) {
      wx.showToast({
        title: '请上传图片',
      })
      return false;
    }
    if (!params.title) {
      wx.showToast({
        title: '请填写标题',
      })
      return false;
    }
    if (!params.content) {
      wx.showToast({
        title: '请添加正文',
      })
      return false;
    }
    if (!params.typeId) {
      wx.showToast({
        title: '请选择类别',
      })
      return false;
    }

    return true;
  },

  async createHandle() {
    if (this.data.submitDisabled) {
      return ;
    }
    this.setData({
      submitDisabled: true
    })
    const params = {
      id: this.data.essayId,
      title: this.data.title,
      content: this.data.content,
      typeId: this.data.typeValue,
      imageUrls: this.data.imageList,
    }
    console.log("createHandle params", params);
    if (this.validParam(params)) {
      await publishEssay(params);
      Toast({
        context: this,
        selector: '#t-toast',
        message: '发布成功',
      });
      setTimeout(() => {
        wx.navigateBack({ delta: 1 });
      }, 1000)
    }
    this.setData({
      submitDisabled: false
    })

  },

  async init() {
    const res = await fetchEssayTypeList();
    this.setData({
      typeList: res.data.map(item => {
        return {
          value: item.id,
          label: item.name
        }
      })
    })
    const res2 = await fetchEssayDetail(this.data.essayId);
    const essay = res2.data;
    this.setData({
      essay: essay
    })
    let typeName = '';
    this.data.typeList.forEach(item => {
      if (item.value == essay.typeId) {
        typeName = item.label;
      }
    })
    let defaultFiles = [];
    const urls = essay.imageUrls;
    for(let i = 0; i < urls.length; i ++) {
      defaultFiles.push({
        name: '' + i,
        url: urls[i],
        type: 'image',
        status: 'done'
      })
    }
    this.setData({
      title: essay.title,
      content: essay.content,
      typeName: typeName,
      typeValue: essay.typeId,
      defaultFiles: defaultFiles,
      originFiles: defaultFiles,
      imageList: urls
    })

    console.log(this.data.defaultFiles);
  },

  /**
   * 生命周期函数--监听页面加载
   */
   onLoad(options) {
    this.setData({
      essayId: options.essayId
    })
    this.init();
  },

  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})